package com.sevenwonders.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import com.sevenwonders.core.City.Side;
import com.sevenwonders.util.Helper;

public class Game {
    public static Random rand = new Random(System.nanoTime());

    public static Game myGame;

    private List<Player> players = new ArrayList<Player>();

    public Game() {
        myGame = this;
    }

    public void setup(String playerName, List<String> opponents) {
        if (Helper.isEmpty(opponents) || opponents.size() < 2) {
            throw new IllegalArgumentException("Must have at least 2 opponents");
        }

        if (Helper.isEmpty(playerName)) {
            playerName = "You";
        }

        List<City> cities = new ArrayList<City>();
        cities.addAll(Arrays.asList(City.values()));
        Player player = new Player(playerName);
        player.setCity(cities.remove(rand.nextInt(cities.size())));
        players.add(player);

        for (String opponent : opponents) {
            player = new Player(opponent);
            City city = cities.remove(rand.nextInt(cities.size()));
            city.setSide(rand.nextBoolean() ? Side.A : Side.B);
            player.setCity(city);
            players.add(player);
        }
    }
    
    public void start() {
        
    }

    public List<Player> getPlayers() {
        return players;
    }

    public List<Player> getNeighbors(Player player) {
        if (player == null) {
            return null;
        }

        int playerIndex = 0;

        for (int i = 0; i < players.size(); i++) {
            if (player.equals(players.get(i))) {
                playerIndex = i;
                break;
            }
        }

        List<Player> neighbors = new ArrayList<Player>();

        if (playerIndex == 0) {
            neighbors.add(players.get(players.size() - 1));
            neighbors.add(players.get(1));
        } else if (playerIndex == players.size() - 1) {
            neighbors.add(players.get(playerIndex - 1));
            neighbors.add(players.get(0));
        } else {
            neighbors.add(players.get(playerIndex - 1));
            neighbors.add(players.get(playerIndex + 1));
        }

        return neighbors;
    }

    public int getNumPlayers() {
        return players.size();
    }
}
